package com.jsj.controller;

import com.jsj.domain.Teacher;
import com.jsj.service.ScoureService;
import com.jsj.service.TeacherService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.sun.deploy.net.HttpResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/teacher")
public class TeacherController {
    private TeacherService teacherService;

    @Autowired
    public void setTeacherService(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    @Autowired
    ScoureService scoureService;

    /**
     * 教师信息查询
     */
    @RequestMapping(value = "/queryByUserName/{username}", method = {RequestMethod.POST})
    @ResponseBody
    @PreAuthorize("@ss.hasAnyRoles('teacher,admin')")
    public Teacher queryByUserName(@PathVariable("username") String username) {
        return teacherService.queryByUserName(username);
    }
    @RequestMapping(value = "/xlsF", method = {RequestMethod.POST})
    @ResponseBody
    @PreAuthorize("@ss.hasAnyRoles('teacher,admin')")
    public void getxlsF(String classId, HttpServletResponse response){
        System.out.println("classid: "+classId);

        String fileName = "19101学生成绩" + System.currentTimeMillis() + ".xls";
        //创建HSSFWorkbook
        XSSFWorkbook wb = scoureService.tableToexcel();
        if(wb!=null){
            System.out.println("hahah");
        }
        else{
            System.out.println("wuwuwu");
        }
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
